﻿using MaBlaApp.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MaBlaApp.Data;

/// <summary>
/// 扫码功能辅助类
/// </summary>
public static class BarcodeScannerManager
{
    /// <summary>
    /// 扫码结果事件，通知订阅者处理扫码结果
    /// </summary>
    public static event EventHandler<BarcodeScannerResult>? HandleBarcodeResult;

    private static BarcodeScannerPage _barcodeScannerPage;

    /// <summary>
    /// 扫码页面传递扫码结果
    /// </summary>
    /// <param name="result"></param>
    public static void OnHandleBarcodeResult(string result)
    {
        HandleBarcodeResult?.Invoke(null, new BarcodeScannerResult(result));
    }

    /// <summary>
    /// 调用者打开扫码页面
    /// </summary>
    /// <returns></returns>
    public static async Task StartScan()
    {
        //Ask for permission first
        bool allowed = false;
        allowed = await BarcodeScanner.Mobile.Methods.AskForRequiredPermission();
        if (allowed)
        {
            if (_barcodeScannerPage is null)
            {
                _barcodeScannerPage = new BarcodeScannerPage();
            }

            _barcodeScannerPage.SetScannig(true);

            Application.Current.MainPage.Navigation.PushModalAsync(_barcodeScannerPage);
        }
        else
        {
            Application.Current.MainPage.DisplayAlert("Alert", "You have to provide Camera permission", "Ok");
        }
    }
}

/// <summary>
/// 扫码结果
/// </summary>
public class BarcodeScannerResult : EventArgs
{
    public string Result;
    public BarcodeScannerResult(string result)
    {
        Result = result;
    }
}
